package com.o2o.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具 提供了对cookie的查询 保存 删除
 * 
 * @author soft01
 * 
 */
public class CookieUtil {
	// 缺省的路径
	private static String path = "/o2o-online";
	// cookie缺省的生存时间
	private static int age = 365 * 24 * 3600;

	/**
	 * 
	 * @param name
	 * @param value
	 * @param age
	 * @param response
	 */
	public static void addCookie(String name, String value, int age,
			HttpServletResponse response) throws UnsupportedEncodingException {
		Cookie cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
		System.out.println("cookie:" + cookie);
		cookie.setMaxAge(age);
		cookie.setPath(path);
		response.addCookie(cookie);
	}

	/**
	 * 
	 * @param name
	 * @param value
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	public static void addCookie(String name, String value,
			HttpServletResponse response) throws UnsupportedEncodingException {
		addCookie(name, value, age, response);
	}

	/**
	 * 
	 * @param name
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String findCookie(String name, HttpServletRequest request)
			throws UnsupportedEncodingException {
		Cookie[] cookies = request.getCookies();
		String value = null;
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie curr = cookies[i];
				if (curr.getName().equals(name)) {
					value = URLDecoder.decode(curr.getValue(), "utf-8");
				}
			}
		}
		return value;
	}

	public static void delete(String name, HttpServletResponse response) {
		Cookie cookie = new Cookie(name, "");
		cookie.setMaxAge(0);
		cookie.setPath(path);
		response.addCookie(cookie);
	}
	
	
}